#!/bin/bash

# env
env_file="/root/__env__"
if [ -f "$env_file" ];then
	. "$env_file"
fi

(
    name=ubuntu
    uid=1000

    # jupyter notebook workdir
    if [ -z "$notebook_dir" ];then
        notebook_dir="/data/jupyter_notebook"
        if [ "$____MODE____" == "debug" ];then
            notebook_dir="/data/jupyter_notebook_debug"
        fi
        if [ ! -e "$notebook_dir" ];then
            mkdir -p "$notebook_dir"
        fi
    fi

    # first_run: set pip index ; passwd 
    if [ ! -e "/first_run" ] || [ ! -e "/home/$name" ];then
        
        pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple

        # set sshd 
        sed -i -E 's/#?PermitRootLogin prohibit\-password/PermitRootLogin yes/' /etc/ssh/sshd_config

        _pass="$PASSWD"
        if [ -z "$_pass" ];then
            _pass="$name"
        fi
    
        echo "root:root$_pass" | chpasswd
        
        (
            groupadd --gid $uid $name
            if [ -e "/home/$name" ];then
                useradd --shell /bin/bash --uid $uid --gid $uid --password "$(openssl passwd "$_pass")" --home-dir /home/$name $name
            else
                useradd --shell /bin/bash --uid $uid --gid $uid --password "$(openssl passwd "$_pass")" --create-home --home-dir /home/$name $name
            fi
            usermod -aG sudo $name
        )

        if [ ! -e "/home/$name/.config" ];then
            if [ -e /etc/home_config/ ];then
                cp -r /etc/home_config/ /home/$name/.config
            fi

            cp -r /root/* /home/$name
        fi
        chown -R $name:$name /home/$name

        ##
        echo "main::$(date)" > "/first_run"
    fi

    # ssh pubkey
    if [ -e "/data/authorized_keys" ] &&  [ ! -e "/root/.ssh/authorized_keys" ];then
        if [ ! -e /root/.ssh/ ];then
            mkdir /root/.ssh/
        fi
        cp /data/authorized_keys /root/.ssh/authorized_keys
        chown root:root /root/.ssh/authorized_keys

        if [ ! -e /home/$name/.ssh/ ];then
            mkdir /home/$name/.ssh/
        fi

        cp /data/authorized_keys /home/$name/.ssh/authorized_keys
        chown $name:$name /home/$name/.ssh/authorized_keys
    fi
)

service ssh restart
if [ -f /entrypoint ];then
    # init for xrdp
	bash /entrypoint true
fi

if [ -n "$1" ]; then
    exec "$@"
fi

tail -f /dev/null

exit 0


# if which jupyter ;then
#     # OTHER_ARGS
#     jupyter notebook --no-browser --ip="*" --allow-root --notebook-dir="$notebook_dir" $OTHER_ARGS
# else
#     tail -f /dev/null
# fi

